package com.fjnu.dao.impl;

import com.fjnu.annotation.PerformanceMonitor;
import com.fjnu.dao.UserDao;
import com.fjnu.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;

@Repository
@Slf4j
public class UserDaoImpl implements UserDao {

    @Override
    @CacheEvict(value = {"users", "usersByRole"}, allEntries = true)
    public int insert(User user) {
        log.info("插入用户: {}", user.getName());
        return 1;
    }

    @Override
    @CacheEvict(value = {"users", "usersByRole"}, allEntries = true)
    public int delete(String userId) {
        log.info("删除用户: {}", userId);
        return 1;
    }

    @Override
    @CacheEvict(value = {"users", "usersByRole"}, allEntries = true)
    public int update(String userId, User user) {
        log.info("更新用户: {}", userId);
        return 1;
    }

    @PerformanceMonitor(alarmedTime = 500)
    @Cacheable(value = "users", key = "#name + '-' + #password")  // 使用Spring的Cacheable
    @Override
    public User selectUserByNameAndPassword(String name, String password) {
        log.info("执行数据库查询: selectUserByNameAndPassword({}, {})", name, password);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return null;
        }

        User user = new User();
        user.setName(name);

        return user;
    }

    @PerformanceMonitor(alarmedTime = 2000)
    @Cacheable(value = "usersByRole", key = "#role")  // 使用Spring的Cacheable
    @Override
    public List<User> selectUserByRole(String role) {
        log.info("执行数据库查询: selectUserByRole({})", role);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return Arrays.asList();
        }

        User user = new User();
        user.setName("adminUser");
        return Arrays.asList(user);
    }
}